package com.javaee;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import java.sql.SQLException;

/**
 * 统一异常处理
 */
@ControllerAdvice
public class GlobalExceptionHandleController {
	private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandleController.class);

	@ExceptionHandler(value = Exception.class)
	public String exceptionHandler(Exception e, Model model) {
		String message = "";
		// 记录异常信息
		logger.error("捕获到异常: ", e);
		// 数据库异常
		if (e instanceof SQLException) {
			message = "数据库异常";
		} else if (e instanceof NoLoginException) {
			message = "未登录";
		} else { // 未知异常
			message = "未知异常";
		}
		model.addAttribute("mymessage", message);
		return "myError";
	}
}
